﻿	
	//var webserver_url = "localhost:8888";
	var webserver_url = "172.16.65.21:8080";
	//var webserver_url = "172.16.96.68:8080";
	//var webserver_url = "http://srv1.buudiengis.com:8080";
	var workspace = "GT";
	var geoserver_url = "http://" + webserver_url + "/geoserver";
	var server_featuretype = geoserver_url + '/rest/workspaces/' + workspace + '/featuretypes.xml';
	var base_layer_name = "xaphuong_region";
	var layer_arr_init = new Array();//Cac layers lay tu geoserver
	var layer_arr = new Array();
	var name_arr =  new Array();//Ten cac layers trong geoserver
	var layer_db_arr = new Array();//Ten va thuoc tinh chia se cac layers trong database
	var mapPanel, tree;
	var map;
	var user_name = '', pass_word = '';	
	/*Mac nhien la nguoi dung binh thuong:
		3: nguoi dung binh thuong
		2: nguoi trong so nganh khac
		1: nguoi trong so nganh
	*/		
	var user_type = 3;//Mac nhien la nguoi dung binh thuong
	
function removeLayers(){
	//Xoa tat ca cac layers trong map ngoai tru lop nen
	numOfLayer =  map.getNumLayers();
	var layers = map.layers;
	var temp_base = map.getLayersByName(base_layer_name)[0];
	
	for (i = 0; i < numOfLayer; i++){					
		map.removeLayer(layers[0]);				
	}		
	//Them lai lop nen
	map.addLayer(temp_base);
}
	
function getBaseLayer(base_layer){	
	index = layer_arr_init.length;
	layer_arr_init[index] = new OpenLayers.Layer.WMS(base_layer,
										geoserver_url+'/wms', {
										//layers: "GT:xaphuong_region"
										layers:  base_layer,
										transparent: true
										}, {          
											isBaseLayer: true,
											visibility: true,					
											buffer: 0
										}
								);
	map.addLayer(layer_arr_init[index]);
}

function getLayerFromGeoServerByName(layer_name){				
		//Neu la lop nen
		index = layer_arr_init.length;			
			layer_arr_init[index] = new OpenLayers.Layer.WMS(layer_name,
										geoserver_url+'/wms', {
										//layers: "GT:xaphuong_region"
										layers:  layer_name,
										transparent: true
										}, {          
											isBaseLayer: false,
											visibility: false,					
											buffer: 0
										}
								);
		
		map.addLayer(layer_arr_init[index]);
}

function getLayerFromGeoServer(){		
	$.ajax({
		async: true,
		type: "GET",
		dataType: "xml",
		//crossDomain: true,		
		url: server_featuretype ,
		error: function() {
			alert("error");
		},
		success: function(data){						
			var tenlop = "";
			solop = data.getElementsByTagName('featureType').length;			
			for (j = 0; j < solop; j++){				
				tenlop = data.getElementsByTagName('featureType')[j].childNodes[0].childNodes[0].nodeValue;	
				if(tenlop != base_layer_name && layer_db_arr.indexOf(tenlop) != -1){				
					getLayerFromGeoServerByName(tenlop);
				}
			}			
		},
		beforeSend: function (xhr){ 			
			xhr.setRequestHeader("Authentication", "Basic YWRtaW46Z2Vvc2VydmVy");
		}		
	});		
}

	/********************Tao doi tuong map***********************************/
	map = new OpenLayers.Map({          
			   projection: "EPSG:4326",
			   units: "degrees",
			   maxResolution: 0.107578125,
			   maxExtent: [
						105.227535,9.920258,105.845518,10.327515
				],
				allOverlays: false
				});
				
Ext.onReady(function() {    
	getLayerList(db_server, db_name, user_name, pass_word);
	getBaseLayer(base_layer_name);		
	setTimeout(
		function() {
				//getLayerFromGeoServer();			
		},
		1000);		
	//Them lop vao doi tuong map	
	//alert("layer_arr_init.length = " + layer_arr_init.length);		
	//map.addLayers(layer_arr_init);
	//alert("layer_db_arr=" + layer_db_arr.length);
	//filterLayerByUser();	
	//Tao doi tuong Panel
	
    mapPanel = new GeoExt.MapPanel({
        border: true,
        region: "center",
        // we do not want all overlays, to try the OverlayLayerContainer
       //map: new OpenLayers.Map({allOverlays: false}),
       center: [0, 0],	   
       zoom: 7,
       map: map,
	   items: [{
				xtype: "gx_zoomslider",
				vertical: true,
				height: 100,
				x: 10,
				y: 20,
				plugins: new GeoExt.ZoomSliderTip()
			}],     						
	   //layers: layer_arr,
	   
	   bbar: [{
			xtype: "button",
            text: "Login",
            handler: function() {          
				//Neu nguoi dung dang nhap 
				if(user_type == 3){
					$( "#dialog-form" ).dialog( "open" );
				}else{
					if (confirm("Bạn chắc chắn muốn kết thúc phiên làm việc?")) { 
						removeLayers();
						user_name = '';
						pass_word = '';
						user_type = 3;
						$("#ext-gen15").attr('value','Login');
						db_server = default_server;
						db_name = default_database;
						//getLayerFromGeoServer();
						getLayerList(db_server, db_name, user_name, pass_word);	
						//getLayerListFromOrtherDB(db_server, db_name, user_type)
					}						
				}				
            }
			},{
				xtype: "button",
				text: "Geo Server",
				handler: function() {					
					
				}
			},
			{
				xtype: "button",
				text: "Chọn sở ngành",
				handler: function() {
					getSoNganh("localhost","postgis");					
					//db_server = "localhost";
					//db_name = "postgis20";
					//getLayerListFromOrtherDB(db_server, db_name, user_type);
				}
			}
		]	   
    });
	
	//them button dang nhap
	
    // create our own layer node UI class, using the TreeNodeUIEventMixin
    var LayerNodeUI = Ext.extend(GeoExt.tree.LayerNodeUI, new GeoExt.tree.TreeNodeUIEventMixin());
        
    // using OpenLayers.Format.JSON to create a nice formatted string of the
    // configuration for editing it in the UI
    var treeConfig = [{
        nodeType: "gx_baselayercontainer"
    }, {
        nodeType: "gx_overlaylayercontainer",
        expanded: true,
        loader: {
             baseAttrs: {
             uiProvider: "layernodeui",
			 checked: false
            }
        }
    }, {     
        loader: {
            param: "LAYERS"
        }
    }];
    // The line below is only needed for this example, because we want to allow
    // interactive modifications of the tree configuration using the
    // "Show/Edit Tree Config" button. Don't use this line in your code.
    treeConfig = new OpenLayers.Format.JSON().write(treeConfig, false);

    // create the tree with the configuration from above
	
    tree = new Ext.tree.TreePanel({
        border: true,
        region: "west",
        title: "Layers",
        width: 200,
        split: true,
        collapsible: true,
        collapseMode: "mini",
        autoScroll: true,
        
        loader: new Ext.tree.TreeLoader({
            // applyLoader has to be set to false to not interfer with loaders
            // of nodes further down the tree hierarchy
            applyLoader: false,
            uiProviders: {
                "layernodeui": LayerNodeUI
            }
        }),
        root: {
            nodeType: "async",
            // the children property of an Ext.tree.AsyncTreeNode is used to
            // provide an initial set of layer nodes. We use the treeConfig
            // from above, that we created with OpenLayers.Format.JSON.write.
            children: Ext.decode(treeConfig)
            // Don't use the line above in your application. Instead, use
            //children: treeConfig
            
        },       
        rootVisible: false,
        lines: false
        
    });
	
    new Ext.Viewport({
        layout: "fit",
        hideBorders: true,
        items: {
            layout: "border",
            deferredRender: false,
            items: [mapPanel, tree]
        }
    });
	
	var username = $( "#username" ),           
        password = $( "#password" );
		
    /*************Form Dang nhap********************/
        $( "#dialog-form" ).dialog({
            autoOpen: false,
            height: 300,
            width: 350,
            modal: true,
            buttons: {
                "Login": function() {
					//alert('username:' + username.val() + '- password: '+ password.val());
					isLogin(username.val(), password.val(), db_server, db_name);
					//Luu lai username va password
					user_name = username.val();
					pass_word = password.val();
					username.val('');
					password.val('');
					$( this ).dialog( "close" );
                },
                Cancel: function() {
					username.val('');
					password.val('');
                    $( this ).dialog( "close" );
                }
            },
            close: function() {
                
            }
        });
		
	/*************End Form Dang nhap********************/	
	/*************Dialog hien thi danh sach so nganh********************/	
	$( "#dialog" ).dialog({
            autoOpen: false,
            show: "blind",
            hide: "explode",
			buttons: {
                "Ok": function() {
					var s = "";
					//Lay ra url nhung so nganh duoc chon					
					$(".chk_songanh:checked").each(function(){
											  	db_server = $(this).val();	
												//alert('server:' + db_server + '- db_name:' + db_name + '- username: ' + user_name + '-pass:' + pass_word );
												getLayerListFromOrtherDB(db_server, db_name, user_name, pass_word);
											  });
					$( this ).dialog( "close" );
                },
                Cancel: function() {
                    $( this ).dialog( "close" );
                }
            },
            close: function() {
                
            }
        });
	/*************End - Dialog hien thi danh sach so nganh**************/	
});

function duyetArr()
{
	var string="";
	var lop_arr =  new Array();
	var i = 0;
	$.get(server_featuretype ,function(data){				
				$(data).find('featureType').each(function(){	
					var $layer = $(this);
					lop_arr[i]="BD:" + $layer.find('name').text();	
					i++;		
				})
	});	
	alert("Luu tru cac lop ban do");
	for(var j=0;j<lop_arr.length-1;j++){
		string+="<a href=\""+vt_url+lop_arr[j]+vt_type+"\">"+lop_arr[j]+"</a></br>";		
	}
	//alert(string);
	document.getElementById('luutru').innerHTML=string;
}

